#!/usr/bin/env python
# -*- coding: utf-8 -*- #   
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import cgi
from google.appengine.api import users
import Cookie,urllib
from django.utils import simplejson
from google.appengine.api import urlfetch

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp.util import run_wsgi_app
import time
from google.appengine.ext import db
import SiteType

class ShowArt(webapp.RequestHandler):
	def get(self):
		url=self.request.uri
		admined=SiteType.Admined(self)
		thekey=SiteType.getkey(url,'show/','?block')
		self.response.out.write(u"""<head>
<script type="text/javascript">
function validate_form(thisform)
{
with (thisform)
  {
 var str=replycontent.value;
  if (str.length>=500)
  { 
  alert("对不起，评论不能超过500字节");
  return false;
  }
 
  return true;
  }
}
</script>
</head>""")
		art=db.get(thekey)
		block=db.get(art.belongto)
		user=SiteType.Header(self,art.title)
		self.response.out.write(u"""<div align="left"><a href="/forum/block/%s">返回上层</a></div>
		<div align="center"><fieldset><legend>楼主：</legend>"""%block.key())
		self.response.out.write(u"""<font size="+1" color="#FFA500">%s</font><br>"""%art.title)
		self.response.out.write(u"""<div align="left"><table width="100%"　border="0" cellspacing="0" cellpadding="0" style="TABLE-LAYOUT: fixed; WORD-BREAK: break-all"><td style="WORD-BREAK: break-all; WORD-WRAP: break-word">""")
		self.response.out.write(art.content)
		self.response.out.write(u"</td></table></div>")
		self.response.out.write(u"""<div align="right">%s发表于"""%art.author+u"""%s</div></fieldset><fieldset><legend>评论</legend>"""%art.date)
		replys=db.GqlQuery("SELECT * FROM Reply WHERE tokey='%s' ORDER BY date"%thekey)
		art.num_reply=replys.count()
		i=1
		for re in replys:
			self.response.out.write(u"%s楼:&nbsp;&nbsp;&nbsp;&nbsp;"%i)
			if re.author:
				self.response.out.write('<b>%s</b> Says at :' % re.author.nickname())
			else:
				self.response.out.write('%s:'%re.ip)
			self.response.out.write(re.date)
			self.response.out.write(u"""<div align="left"><table width="100%"　border="0" cellspacing="0" cellpadding="0" style="TABLE-LAYOUT: fixed; WORD-BREAK: break-all"><td style="WORD-BREAK: break-all; WORD-WRAP: break-word">""")
			self.response.out.write('<br><blockquote>%s</blockquote>' %
                                    cgi.escape(re.content))
                        self.response.out.write(u"</td></table></div>")
                        if admined:
                        	self.response.out.write(u"""<div align="right"><a href="/art/delreply?reply=%s">删除评论</a>"""%re.key())
                        i=i+1
		self.response.out.write(u"""<body><form action="/art/reply" onsubmit="return validate_form(this);" method="post">
				<div><textarea name="replycontent" rows="3" cols="60"></textarea></div>
				<div><input type="submit" value="评论"></div>
				<div><type="text" name="thekey" value="%s" visible=0></div>
			</form></body></fieldset>"""%thekey)
		SiteType.Ender(self)

class Edit(webapp.RequestHandler):
	def get(self):
		user=SiteType.Header(self)
		self.response.out.write(u"""<div align="center">""")
		if SiteType.ismember(user):
			url=self.request.uri
			thekey=SiteType.getkey(url,'edit?block=')
			block=db.get(thekey)
			self.response.out.write(self.response.out.write(u"""
				<form action="/art/pub" method="post">
				<div>标题：<input type="text" name="title"></div>
				<div>板块：%s<div>"""%block.name+u"""
				<div><textarea name="content2" rows="10" cols="60"></textarea></div>
				<div><input type="submit" value="发表"></div>
			</form>"""))
		else:
			self.response.out.write(u"对不起，您没有进行此操作的权限")	
		self.response.out.write(u"</div>")	
		SiteType.Ender(self)
class ReP(webapp.RequestHandler):
	def post(self):
		re=SiteType.Reply()
		re.content = self.request.get('replycontent')
		re.tokey=self.request.headers['referer']
		re.tokey=SiteType.getkey(re.tokey,'show/','?block')
		art=SiteType.Article()
		art=db.get(re.tokey)
		if art.num_reply:
			pass
		else:
			replys=db.GqlQuery("SELECT * FROM Reply WHERE tokey='%s' ORDER BY date"%re.tokey)
			art.num_reply=replys.count()
		art.num_reply+=1
		art.put()
		
		if users.get_current_user():
			re.author = users.get_current_user()
		else:
			re.ip=str(self.request.remote_addr)
		re.put()
		self.redirect(self.request.headers['referer'])
class Pub(webapp.RequestHandler):
	def post(self):
		user=users.get_current_user()
		thekey=self.request.headers['referer']
		thekey=SiteType.getkey(thekey,'block=')
		if user:
			if SiteType.ismember(user):
				art=SiteType.Article()
				art.title=self.request.get('title')
				art.content = self.request.get('content2').replace('\n',"<br>")
				art.num_reply=0
				art.belongto=thekey
				art.author=user
				art.put()
		self.redirect('/forum/block/%s'%thekey)

class DelArt(webapp.RequestHandler):
	def get(self):
		user=users.get_current_user()
		thekey=self.request.url
		thekey=SiteType.getkey(thekey,'art=')	
		if user:
			if SiteType.isadmin(user):
				db.delete(thekey)
		self.redirect(self.request.headers['referer'])
class DelRp(webapp.RequestHandler):
	def get(self):
		user=users.get_current_user()
		thekey=self.request.url
		thekey=SiteType.getkey(thekey,'reply=')	
		if user:
			if SiteType.isadmin(user):
				db.delete(thekey)
		self.redirect(self.request.headers['referer'])
class CreateNews(webapp.RequestHandler):
	def get(self):
		user=users.get_current_user()
		thekey=self.request.url
		thekey=SiteType.getkey(thekey,'art=')
		art=db.get(thekey)
		if user:
			if SiteType.isadmin(user):
				news=SiteType.News()
				news.NewsTitle=art.title
				news.NewsURL="/art/show/%s"%art.key()
				news.put()
		self.redirect(self.request.headers['referer'])	
def main():
  application = webapp.WSGIApplication([('/art/show/.*', ShowArt),('/art/edit.*',Edit),('/art/pub.*',Pub),('/art/reply',ReP),('/art/delart.*',DelArt),('/art/delreply.*',DelRp),('/art/createnews.*',CreateNews)],
                                       debug=True)
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()
